<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" :width="900"
        destroy-on-close :close-on-click-modal="false" @closed="$emit('closed')">
        <el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="100px"
            label-position="right" v-loading.fullscreen="loading">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="题干" prop="stem">
						<el-input v-model="form.stem" placeholder="请输入题干" clearable maxlength="255" show-word-limit></el-input>
					</el-form-item>
                </el-col>
            </el-row>
            <el-form-item class="option-item" :label="'选项' + an.prefix" :prop="'options.' + k + '.content'" :rules="[
                    {
                        required: true,
                        validator: (rule, value, callback) => { checkNull(rule, value, callback, k) },
                        trigger: 'blur'
                    }
                ]" v-for="(an, k) in form.options" :key="k">
                <div class="input-item">
                    <div class="flexV">
                        <el-input style="flex: 1;" class="content" v-model="an.content" :maxlength="500"
                            show-word-limit placeholder="请输入选项" />  
                        <div class="options-btn flexV">
                            <el-tooltip class="box-item" effect="dark" content="删除" placement="bottom-start">
                                <el-button :style="`margin-left: 10px;opacity: ${k > 0 ? '1' : '0'}`" type="primary"
                                    icon="el-icon-delete" circle
                                    @click="form.options.length > 1 ? deleteOption(k) : ''">
                                </el-button>
                            </el-tooltip>
                        </div>
                    </div>
                </div>
            </el-form-item>
            <el-button icon="fe-plus" size="small" @click="addOption" style="margin-left: 100px;margin-bottom: 15px" v-if="form.options.length <= 10">添加选项</el-button>
           
            <el-form-item style="margin-top: 15px" label="答案" prop="rightAnswer" v-if="form.type == 1 || form.type == 2">
				<el-radio-group v-model="form.rightAnswer" v-if="form.type == 1" size="">
					<el-radio :label="an.prefix" v-for="(an,k) in form.options" :key="k">{{an.prefix}}</el-radio>
				</el-radio-group>
				<el-checkbox-group v-model="form.correctsArray" v-if="form.type == 2" @change="form.rightAnswer = form.correctsArray.sort().join(',')" size="">
					<el-checkbox :label="an.prefix" v-for="(an,k) in form.options" :key="k">{{an.prefix}}</el-checkbox>
				</el-checkbox-group>
			</el-form-item>
            <el-form-item label="解析" prop="analysis">
                <el-input :rows="5" type="textarea" v-model="form.analysis" placeholder="请输入解析" clearable maxlength="2000" show-word-limit></el-input>
			</el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="visible = false">取 消</el-button>
            <el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
        </template>
    </el-dialog>

    
</template>

<script>
import { defineAsyncComponent } from 'vue'
import { in_array } from '@/utils/index.js'
const scEditor = defineAsyncComponent(() => import('@/components/scEditor'))
export default {
    components: {
        scEditor,
    },
    emits: ['success', 'closed'],
    data() {
        return {
            in_array,
            mode: "add",
            titleMap: {
                add: '新增题目',
                edit: '编辑题目',
            },
            dialog: {
                drag: false,
                knock: false,
            },
            visible: false,
            loading: false,
            isSaveing: false,
            article: null,
            form: this.getDefaultRuleForm(),
            //验证规则
            rules: {
                stem: [
                    { required: true, message: '请输入题干', trigger: 'blur' },
                ],
                rightAnswer: [
                    {required: true, message: '请选择答案', trigger: 'blur'},
                    {
                        validator: (rule, value, callback) => {
                            if (value == '' && (this.form.type == 1 || this.form.type == 2)) {
                                callback(new Error('请选择答案'));
                            } else {
                                if (value.length > 500) {
                                    callback(new Error('参考答案最多500字'));  
                                } else {
                                    callback();
                                }
                            }
                        }, trigger: 'change'
                    }
				],
                analysis: [
                    {max: 2000, message: '解析最多2000个字', trigger: 'blur'}
                ],
            },
            prefix: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
        }
    },
    computed: {
        
    },
    mounted() {
        
    },
    methods: {
        //显示
        open(mode = 'add', type, article) {
            this.mode = mode
            this.article = article
            if (this.mode == 'add') {
                this.resetFrom()
            }
            if (type) {
                this.form.type = type;
            }
            this.visible = true
            return this
        },
        resetFrom() {
            this.form = this.getDefaultRuleForm()
            this.form.articleId = this.article.id
        },
        //自定义检测选项
        checkNull(rule, value, callback, k) {
            if (in_array(this.form.type, [1, 2])) {
                return callback();
            } else {
                return callback();
            }
        },
        // 题干附件相关结束
        addOption() {
            this.form.options.push({
                prefix: '',
                content: ''
            })
            this.form.options.forEach((e, k) => {
                e.prefix = this.prefix[k]
            })
        },
        deleteOption(k) {
            this.form.options.splice(k, 1);
            this.form.options.forEach((e, k) => {
                e.prefix = this.prefix[k]
            })
        },
        //表单提交方法
        async submit() {
            
            if (!await this.$refs.dialogForm.validate().catch(() => { return false })) {
                return false
            }

            let _data = {
                id: this.form.id,
                articleId: this.form.articleId,
                stem: this.form.stem,
                type: this.form.type,
                analysis: this.form.analysis,
                rightAnswer: '',
                options: []
            }
            if (this.form.rightAnswer) {
                _data.rightAnswer = this.form.rightAnswer.split(",")
            }

            this.form.options.forEach(item => {
                let _option = {
                    prefix: item.prefix,
                    content: item.content || ''
                }
                _data.options.push(_option)
            })

            this.isSaveing = true;
            if (_data.id) {
                await this.$API.articleQuestion.action.put(_data).then(res => {
                    this.visible = false;
                    if (res.error == 0) {
                        this.$emit('success')
                        this.$notify.success("保存成功")
                    }else{
                        this.$notify.error(res.message)
                    }
                }).finally(() => { 
                    this.isSaveing = false; 
                })
            } else {
                await this.$API.articleQuestion.action.post(_data).then(res => {
                    this.visible = false;
                    if (res.error == 0) {
                        this.$emit('success')
                        this.$notify.success("保存成功")
                    }else{
                        this.$notify.error(res.message)
                    }
                }).finally(() => { 
                    this.isSaveing = false; 
                })
            }

        },
        //表单注入数据
        async setData(row = null) {
            this.loading = true
			await this.$API.articleQuestion.action.get({ id: row.id }).then(res => {
				let _form = {
					id: res.data.id,
					stem: res.data.stem,
                    articleId: res.data.article ? res.data.article.id : null,
                    type: res.data.type ? res.data.type.value : '',
                    rightAnswer: res.data.rightAnswer.join(','),
                    correctsArray: res.data.rightAnswer ? res.data.rightAnswer : [],
                    analysis: res.data.analysis,
                    options: []
				}
                
                if (res.data.options) {
                    let optionsArr = res.data.options
                    _form.options = [];
                    optionsArr.forEach(item => {
                        let _option = {
                            prefix: item.prefix,
                            content: item.content,
                        }
                        _form.options.push(_option)
                    })
                }
                
                console.log('_form', _form)
                this.form = _form
				this.loading = false
			}, () => {
                this.loading = false
            })
        },
        getDefaultRuleForm() {
            return {
                id: null,
                articleId: null,
                type: null,
                stem: '',
                analysis: '',
                rightAnswer: '',
                correctsArray: [],
                options: [
                    {
                        prefix: 'A',
                        content: '',
                    }
                ]
            }
        }
    }
}
</script>

<style>
    .sc-upload .sc-upload-file .image img {object-fit: contain;}
    /* 给个最小宽高,防止有空的<img>标签 */
    .ck-editor__main .image.ck-widget img {min-width: 100px; min-height: 100px;}
</style>

<style scoped>
.el-tag {
    margin-left: 0 !important;
    margin-right: 10px !important;
}

/deep/ .ck.ck-editor__main>.ck-editor__editable {
    height: 200px !important;
}
</style>
